package com.example.jasonsun.sharelib;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Window;

import com.example.jasonsun.sharelib.config.Cache;
import com.example.jasonsun.sharelib.platform.QQPlatform;
import com.example.jasonsun.sharelib.platform.QZonePlatform;
import com.example.jasonsun.sharelib.platform.SharePlatform;
import com.example.jasonsun.sharelib.platform.WeichatPlatform;
import com.example.jasonsun.sharelib.platform.XlWeiboPlatform;
import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.IWeiboHandler;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.constant.WBConstants;

/**
 * 透明Activit
 */
public class FakeActivity extends Activity implements IWeiboHandler.Response {
    public static final String EXTRA_PLATFORM_ID = "platform_id";
    public static final String EXTRA_IS_LOGIN = "is_login";
    public static final String EXTRA_TITLE = "title";
    public static final String EXTRA_DESC = "desc";
    public static final String EXTRA_IMG_URL = "img_url";
    public static final String EXTRA_WEB_URL = "web_url";

    /**
     * 微博微博分享接口实例
     */
    private IWeiboShareAPI mWeiboShareAPI = null;
    private int mPlatformId;
    private boolean mIsLogin = false;
    private SharePlatform mPlatform;
    private String mTitle;
    private String mDesc;
    private String mImgUrl;
    private String mWebUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        if (!getIntent().hasExtra(EXTRA_IS_LOGIN) && !getIntent().hasExtra(EXTRA_PLATFORM_ID)) {
            finish();
            return;
        }
        mPlatformId = getIntent().getIntExtra(EXTRA_PLATFORM_ID, -1);
        boolean isLogin = getIntent().getBooleanExtra(EXTRA_IS_LOGIN, false);

        if (!isLogin) {
            mTitle = getIntent().getStringExtra(EXTRA_TITLE);
            mDesc = getIntent().getStringExtra(EXTRA_DESC);
            mImgUrl = getIntent().getStringExtra(EXTRA_IMG_URL);
            mWebUrl = getIntent().getStringExtra(EXTRA_WEB_URL);
        }

        if (isLogin) {
            login(mPlatformId);
        } else {
            share(mPlatformId);
        }

        // 创建微博分享接口实例
        mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(this, Cache.sina_app_key);
//        mWeiboShareAPI.registerApp();

        // 当 Activity 被重新初始化时（该 Activity 处于后台时，可能会由于内存不足被杀掉了），
        // 需要调用 {@link IWeiboShareAPI#handleWeiboResponse} 来接收微博客户端返回的数据。
        // 执行成功，返回 true，并调用 {@link IWeiboHandler.Response#onResponse}；
        // 失败返回 false，不调用上述回调
        if (savedInstanceState != null) {
            mWeiboShareAPI.handleWeiboResponse(getIntent(), this);
        }
    }

    public static void startThisActivityForShare(Context context, int platNo, String title, String desc, String imgUrl,
                                                 String webUrl) {
        Intent i = new Intent(context, FakeActivity.class);
        i.putExtra(EXTRA_PLATFORM_ID, platNo);
        i.putExtra(EXTRA_IS_LOGIN, false);
        i.putExtra(EXTRA_TITLE, title);
        i.putExtra(EXTRA_DESC, desc);
        i.putExtra(EXTRA_IMG_URL, imgUrl);
        i.putExtra(EXTRA_WEB_URL, webUrl);
        context.startActivity(i);
    }

    public static void startThisActivityForLogin(Context context, int platNo) {
        Intent i = new Intent(context, FakeActivity.class);
        i.putExtra(EXTRA_PLATFORM_ID, platNo);
        i.putExtra(EXTRA_IS_LOGIN, true);
        context.startActivity(i);
    }

    private void share(int platformId) {
        mPlatform = null;
        switch (platformId) {
            case SharePlatform.WECHAT_SESSION:
                mPlatform = new WeichatPlatform(this);
                break;
            case SharePlatform.WECHAT_CIRCLE:
                mPlatform = new WeichatPlatform(this);
                break;
            case SharePlatform.QQ_FRIENDS:
                mPlatform = new QQPlatform(this);
                break;
            case SharePlatform.QZONE:
                mPlatform = new QZonePlatform(this);
                break;
            case SharePlatform.XINLANG_WEIBO:
                mPlatform = new XlWeiboPlatform(this, null);
                break;
            default:
                break;
        }

        if (mPlatform != null) {
            mPlatform.share(platformId, mTitle, mDesc, mImgUrl, mWebUrl);
        }
    }

    public void login(int platformId) {
        mPlatform = null;
        switch (platformId) {
            case SharePlatform.WECHAT_SESSION:
                mPlatform = new WeichatPlatform(this);
                break;
            case SharePlatform.QQ_FRIENDS:
                mPlatform = new QQPlatform(this);
                break;
            case SharePlatform.XINLANG_WEIBO:
                mPlatform = new XlWeiboPlatform(this, null);
                break;
            default:
                break;
        }

        if (mPlatform != null) {
            mPlatform.login();
        }
    }

    /**
     * 当 SSO 授权 Activity 退出时，该函数被调用。
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mPlatformId == SharePlatform.XINLANG_WEIBO && mIsLogin) {
            ((XlWeiboPlatform) mPlatform).getSsoHandler().authorizeCallBack(requestCode, resultCode, data);
        }
    }

    /**
     * @see {@link Activity#onNewIntent}
     */
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        // 从当前应用唤起微博并进行分享后，返回到当前应用时，需要在此处调用该函数
        // 来接收微博客户端返回的数据；执行成功，返回 true，并调用
        // {@link IWeiboHandler.Response#onResponse}；失败返回 false，不调用上述回调
        if (mPlatformId == SharePlatform.XINLANG_WEIBO && !mIsLogin) {
            mWeiboShareAPI.handleWeiboResponse(intent, this);
        }
    }

    /**
     * 接收微客户端博请求的数据。
     * 当微博客户端唤起当前应用并进行分享时，该方法被调用。
     *
     * @param baseResp 微博请求数据对象
     * @see {@link IWeiboShareAPI#handleWeiboRequest}
     */
    @Override
    public void onResponse(BaseResponse baseResp) {
        if (baseResp != null) {
            switch (baseResp.errCode) {
                case WBConstants.ErrorCode.ERR_OK:
//                    Toast.makeText(this, R.string.weibosdk_demo_toast_share_success, Toast.LENGTH_LONG).show();
//                    ShareInstance.getInstance().receiveMessage(true, null, 0, null);
                    break;
                case WBConstants.ErrorCode.ERR_CANCEL:
//                    Toast.makeText(this, R.string.weibosdk_demo_toast_share_canceled, Toast.LENGTH_LONG).show();
                    ShareInstance.getInstance().receiveMessage(false, null, -1, "cancel");
                    break;
                case WBConstants.ErrorCode.ERR_FAIL:
//                    Toast.makeText(this, getString(R.string.weibosdk_demo_toast_share_failed) + "Error Message: " + baseResp.errMsg,
//                            Toast.LENGTH_LONG).show();
                    ShareInstance.getInstance().receiveMessage(false, null, -1, baseResp.errMsg);
                    break;
            }
        } else {
            ShareInstance.getInstance().receiveMessage(false, null, -1, "unknown");
        }

        finish();
    }
}
